package com.example.mr5.bluetoothppt;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.example.mr5.bluetoothppt.Util.SocketUtil;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class BluetoothPPTActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private final static String TAG ="BluetoothPPTActivity";
    private final static int MSG_CONNECT_SUCCEED = 1;
    private final static int MSG_CONNECT_FAILE = 2;
    private ListView deviceList;
    private ImageButton refreshDevice;

    private static final UUID uuid = UUID.fromString("3F2504E0-4F89-11D3-9A0C-0305E82C3301");
    private BluetoothAdapter blueToothAdapter = BluetoothAdapter
            .getDefaultAdapter();

    private ArrayList<HashMap<String, String>> list = null;
    private List<BluetoothDevice> _devices = new ArrayList<BluetoothDevice>();
    private BluetoothDevice device = null;
    private BluetoothSocket btSocket = null;
    private OutputStream outStream = null;
    private ConnectTask mTask;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        showDevices();
    }

    private void initView() {
        deviceList = (ListView) findViewById(R.id.device_list);
        refreshDevice = (ImageButton) findViewById(R.id.refresh_btn);
        deviceList.setOnItemClickListener(this);
        progressBar = (ProgressBar) findViewById(R.id.connect_progress);

    }

    public void showDevices() {
        Set<BluetoothDevice> devices = blueToothAdapter.getBondedDevices();
        list = new ArrayList<HashMap<String, String>>();
        if (devices.size() > 0) {
            Iterator<BluetoothDevice> it = devices.iterator();
            BluetoothDevice bluetoothDevice = null;
            HashMap<String, String> map;
            while (it.hasNext()) {
                map = new HashMap<String, String>();
                bluetoothDevice = it.next();
                map.put("address", bluetoothDevice.getAddress());
                map.put("name", bluetoothDevice.getName());
                list.add(map);
                _devices.add(bluetoothDevice);
            }
            SimpleAdapter listAdapter = new SimpleAdapter(this, list,
                    R.layout.device_item, new String[] { "address", "name" },
                    new int[] { R.id.address, R.id.name });
            deviceList.setAdapter(listAdapter);
        }
    }

    private boolean connectDevice(String addressStr){
        device = blueToothAdapter.getRemoteDevice(addressStr);
        try {
            BluetoothSocket btSocket =device.createRfcommSocketToServiceRecord(uuid);
            SocketUtil.setBtSocket(btSocket);
        } catch (Exception e) {
            mainHandler.obtainMessage(MSG_CONNECT_SUCCEED,"通信通道创建失败！").sendToTarget();
        }

        if (SocketUtil.getBtSocket() != null) {
                boolean succeed = SocketUtil.connect();
            if(succeed){
                mainHandler.obtainMessage(MSG_CONNECT_SUCCEED,"通信通道连接成功！").sendToTarget();
            }
            return succeed;
        }
        return false;
    }

    public void displayLongToast(String str) {
        Toast toast = Toast.makeText(this, str, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 0, 220);
        toast.show();
    }

    private HashMap<String, String> connectDevice;
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String addressStr = _devices.get(position).getAddress();
        connectDevice = list.get(position);
        mTask = new ConnectTask();
        mTask.execute(addressStr.substring(addressStr.length() - 17));
    }

    private MainHandler mainHandler = new MainHandler();
    private class MainHandler extends android.os.Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            displayLongToast(msg.obj.toString());

        }
    }

    private class ConnectTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute() called");
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(String... params) {
            Log.i(TAG, "doInBackground(Params... params) called");
            return connectDevice(params[0])+"";
        }
        @Override
        protected void onProgressUpdate(Integer... progresses) {
            Log.i(TAG, "onProgressUpdate(Progress... progresses) called");
        }

        @Override
        protected void onPostExecute(String result) {
            Log.i(TAG, "onPostExecute(Result result) called"+result);
            progressBar.setVisibility(View.GONE);
            if(result.equals("true")){
                if(connectDevice!=null){
                    Intent intent = new Intent(BluetoothPPTActivity.this,ControlActivity.class);
                    intent.putExtra("device",connectDevice);
                    startActivity(intent);
                }
            }
        }
        @Override
        protected void onCancelled() {
            Log.i(TAG, "onCancelled() called");
        }
    }
}
